package com.kexun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kexun.common.annotation.LoginManage;
import com.kexun.common.utils.Result;
import com.kexun.controller.base.ApiBaseAction;
import com.kexun.entity.DO.Manage;
import com.kexun.service.ManageService;
import com.kexun.config.websocket.WebSocketServer;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("message")
public class MessageController extends ApiBaseAction {

    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private ManageService manageService;



    @GetMapping("index")
    public String messagePage(Model model) {
        List<Manage> manages = manageService.list();
        model.addAttribute("manages", manages);
        return "message";
    }

    @ResponseBody
    @RequestMapping("send")
    public Result send(@RequestBody String req, @LoginManage Manage manage) throws IOException {
        JSONObject reqJson = JSON.parseObject(req);
        String to = reqJson.getString("to");

        String content = reqJson.getString("content");
        String from = webSocketServer.getUserId();
        HashMap<String, Object> map = new HashMap<>();
        map.put("from", manage.getNickName());
        map.put("content", content);
        map.put("type", 2);
        map.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        String msg = JSON.toJSONString(map);
        if (StringUtils.isEmpty(to)) {
            WebSocketServer.sendAll(msg);
            return Result.success("群发消息成功");
        }
        String s = webSocketServer.sendInfo(msg, to);
        if (s == null) {
            return Result.success("消息发送成功");
        } else {
            return Result.error(s);
        }
    }

}
